package com.wonyesoft.wuliu.acticity;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.wonyesoft.wuliu.AppContent;
import com.wonyesoft.wuliu.R;
import com.wonyesoft.wuliu.acticity.base.BaseActivity;
import com.wonyesoft.wuliu.acticity.utils.StringUtils;
import com.wonyesoft.wuliu.api.GagApi;
import com.wonyesoft.wuliu.model.CarType;
import com.wonyesoft.wuliu.model.CargoInfo;
import com.wonyesoft.wuliu.vo.JsonRequest;
import com.wonyesoft.wuliu.vo.JsonResponse;
import com.wonyesoft.wuliu.vo.State;


public class AddCargoQuickActivity extends BaseActivity implements OnClickListener,
		OnGetGeoCoderResultListener {

	private TabHost mTabHost;
	private RadioGroup mRadioGroup;
	private TextView title, head_right, cargoinfo_cargotypetxt,
			cargoinfo_cargovolumetxt, cargoinfo_cargoweighttxt, driver_time,
			cargoinfo_cargocartypetxt, cargoinfo_cargopay1, driver_guige,
			cargoinfo_cargopay2, a11_common, a12_common,cargoinfo_cargocartypetxtisback;
	private ImageView head_left;
	private EditText driver_carnumber, driver_youhao, driver_youhao2,  driver_leixing,
			driver_long, a8_common;
	private Button driver_baochun, a9_common, a10_common;
	private String passwordString, rePwdString, repwd2String, driverID;
	private RequestParams params;
	private LinearLayout cargoinfo_shrmap, cargoinfo_fhrmap, driver_zaizhong;
	private RelativeLayout cargoinfo_cargotype,cargoinfo_cargocartype;
	private LocationClient mLocationClient;
	private LocationMode tempMode = LocationMode.Hight_Accuracy;
	private String tempcoor = "gcj02";
	private List<CargoInfo> sourceDateList;
	private List<CarType> sourceCarTypeList;
	private String aString;
	public static Gson gson = new Gson();
	private LatLng pt1;
	private LatLng pt2;
	private GeoCoder mSearch = null;
	private double mi = 0.0;
	private int changeId = 0;
	private String carTypeId;
	private int isBackList;
	private int intPayType;
	private int intOrderType;
	private int intCargoType;
	private int intCarType;
	private int intCargoAmount;
	private int intCargoWeight;
	private String intPrice;
 
	private static final int DATE_ID = 1;

	private HttpUtils http = new HttpUtils();

	private int selectedFruitIndex = 0;

	private AppContent app;

	private PreferencesCookieStore preferencesCookieStore;

	private SharedPreferences share;

	private String key = "UserInfo";

	private String seachWords = "重庆市";
	
	private String flowId = null;

	private final String[] arraycargopaytype = new String[] { "线下支付", "在线支付" };

	private final String[] arraycargoisback = new String[] { "有回单", "没有回单" };

	private final String[] arraycargochargetype = new String[] { "到付", "现付" };

	private final String[] arraycargotype = new String[] { "易碎", "易燃", "易爆",
			"一般" };
	private final String[] arraycargoweight = new String[] { "1吨以下", "3吨以内",
			"5吨以内", "5吨以上" };
	private final String[] arraycargovolme = new String[] { "1立方米以内", "3立方米以内",
			"5立方米以内", "5立方米以上" };
	private final String[] arraycargocartype = new String[] { "小箱车(面包,金杯)","0.5T车", "1T车",
			"2T车", "4T车", "5T车", "8T车" };
	private Bundle bundle2;
	private String[] noticeMsg = new String[] { "无", "无", "无" };
	private final String[] arraycargocarnotice = null;

	private int carTypeIds[] = { 1,2,3,4,5,6,7};
	
	private int ownCarTypeId = 0;
	// private SuggestionSearch mSuggestionSearch;
	private EditText c;

	@SuppressLint("NewApi")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.aj_addquickcargo);
		app = (AppContent) getApplication();
		preferencesCookieStore = AppContent.getPreferencesCookieStore();
		mSearch = GeoCoder.newInstance();
		mSearch.setOnGetGeoCodeResultListener(this);
		findIds();
		blindOnclick();
		//getCarType();
		initViews();
	}

	private void initViews() {

		//if(!(StringUtils.isEmpty(sourceDateList.get(0).getPayType())))
        a9_common.setText("议价");
        a9_common.setOnClickListener(this);

	}

	private void ae() {
		c = new EditText(AddCargoQuickActivity.this);
		c.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
		c.setHint("请输入您的期望价格");
		new AlertDialog.Builder(this).setTitle("请输入您的意向金额")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						if ((!StringUtils.isEmpty(c.getText().toString()))
								&& Double.valueOf(c.getText().toString()) > 0) {
							intPrice = c.getText().toString();

							a9_common.setText("￥ " + intPrice);
						} else
							showLongToast("未正确输入金额！");
					}
				}).setNegativeButton("取消", null).setView(c).show();
	}


	//验证提交的数据
	private void checkCargo() {
		if(StringUtils.isEmpty(driver_time.getText().toString())){showLongToast("请选择收货地址");return;}
		if(StringUtils.isEmpty(driver_guige.getText().toString())){showLongToast("请选择发货人联系地址");return;}
		if(ownCarTypeId ==0){showLongToast("未选择车辆类型");return;}
		save();
	}
	
	// alert弹出通用方法
	private void blindAlert(final String[] slearry, String title,
			final TextView txt) {
		Dialog alertDialog = new AlertDialog.Builder(this)
				.setTitle(title)
				.setIcon(R.drawable.ic_launcher)
				.setSingleChoiceItems(slearry, 0,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								selectedFruitIndex = which;
							}
						})
				.setPositiveButton("确认", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						System.out.println(selectedFruitIndex);
						txt.setText(slearry[selectedFruitIndex]);
						if (txt.equals(cargoinfo_cargocartypetxt)) {
							ownCarTypeId = carTypeIds[selectedFruitIndex];
							//toPrice();
						}
						
						selectedFruitIndex = 0;
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				}).create();
		alertDialog.show();

	}

	private void blindOnclick() {
		head_left.setVisibility(0);
		title.setText("快速下单");
		http = new HttpUtils();
		head_left.setOnClickListener(this);
		cargoinfo_shrmap.setOnClickListener(this);
		cargoinfo_fhrmap.setOnClickListener(this);
		a10_common.setOnClickListener(this);
		cargoinfo_cargocartype.setOnClickListener(this);

	}

	private void findIds() {
	
		driver_time = (TextView) findViewById(R.id.driver_time);
		driver_guige = (TextView) findViewById(R.id.driver_guige);
		driver_youhao = (EditText) findViewById(R.id.driver_youhao);
		driver_youhao2 = (EditText) findViewById(R.id.driver_youhao2);
		cargoinfo_shrmap = (LinearLayout) findViewById(R.id.cargoinfo_shrmap);
		cargoinfo_fhrmap = (LinearLayout) findViewById(R.id.cargoinfo_fhrmap);
		// ((AppContent)getApplication()).mLocationResult = driver_time;
		title = (TextView) findViewById(R.id.head_title);
		head_left = (ImageView) findViewById(R.id.head_left);
		a9_common = (Button) findViewById(R.id.a9_common);
		a10_common = (Button) findViewById(R.id.a10_common);
		a11_common = (TextView) findViewById(R.id.a11_common);
		a12_common = (TextView) findViewById(R.id.a12_common);
		cargoinfo_cargocartype =   (RelativeLayout) findViewById(R.id.cargoinfo_cargocartype);
		cargoinfo_cargocartypetxt = (TextView) findViewById(R.id.cargoinfo_cargocartypetxt);
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.head_left:
			finish();
			break;
		case R.id.a9_common:
			ae();
			break;
		case R.id.cargoinfo_cargocartype:
			System.out.println("调用了！");
			blindAlert(arraycargocartype, "请选择货车类型", cargoinfo_cargocartypetxt);
			break;
		case R.id.cargoinfo_shrmap:
			// getLocation();
			// openActivity(AddCargoMapActivity.class);
			Intent intent = new Intent(this, AddCargoMapActivity.class);
			startActivityForResult(intent, 1);
			break;
		case R.id.cargoinfo_fhrmap:
			// openActivity(AddCargoMapActivity.class);
			// getmap();
			Intent intent2 = new Intent(this, AddCargoMapActivity.class);
			startActivityForResult(intent2, 2);
			break;
		case R.id.a10_common:
			checkCargo();
			break;
		default:
			break;
		}
	}

	private void save() {
		if(StringUtils.isEmpty(driver_youhao.getText().toString())||StringUtils.isEmpty(driver_youhao2.getText().toString())) {
			showLongToast("您还有未填选项");
			return;
		}
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("sdAddress", driver_time.getText().toString());
		dataMap.put("reAddress", driver_guige.getText().toString());
		dataMap.put("sdMobile", driver_youhao.getText().toString());
		dataMap.put("reMobile", driver_youhao2.getText().toString());
		dataMap.put("carType", ownCarTypeId);
		dataMap.put("totalFee", intPrice);
		dataMap.put("transPrice", intPrice);
		dataMap.put("orderType", 5);
		JsonRequest jr = JsonRequest.getInit();
		jr.setData(dataMap);
		String json = gson.toJson(jr);
		params = new RequestParams();
		params.addBodyParameter("jsonParam", json);
		System.out.println("json:" + json);
		http.configCookieStore(preferencesCookieStore);
		http.send(HttpRequest.HttpMethod.POST, GagApi.OnlineOrder, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {

						System.out.println("进入添加addcargo");
						Gson gson2 = new Gson();
						JsonResponse jrs = gson2.fromJson(responseInfo.result,
								JsonResponse.class);
						System.out.println(responseInfo.result);
						State state = jrs.getState();
						// System.out.println(preferencesCookieStore);
						if (state.getCode().equals(State.SUCEECCODE)) {
							showLongToast("下单成功，请等待平台审核！");
							//showLongToast(state.getMsg());
							//setListDetails();
							finish();
						} else
							// System.out.println(state.getMsg());
							showLongToast(state.getMsg());
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// testTextView.setText(error.getExceptionCode() + ":" +
						// msg);
						System.out.println(msg);
					}
				});

	}


	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// aString = data.getExtras().getString("addr");
		// System.out.println("resultCode:"+resultCode+"requestCode:"+requestCode);
		if (resultCode == 0)
			return;
		aString = data.getStringExtra("address");
		/*
		 * if(StringUtils.isEmpty(aString = data.getExtras().getString("addr")))
		 * { System.out.println("asting空置"); return;}
		 */

		switch (requestCode) {
		case (1):
			driver_time.setText(aString);
			changeId = 1;
			mSearch.geocode(new GeoCodeOption().city("重庆市").address(aString));
			break;
		case (2):
			driver_guige.setText(aString);
			changeId = 2;
			mSearch.geocode(new GeoCodeOption().city("重庆市").address(aString));
			break;
		default:
			break;
		}
	}



	@Override
	public void onGetGeoCodeResult(GeoCodeResult result) {
		System.out.println("geo" + "进来了");
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			System.out.println("有问题");
			Toast.makeText(this, "抱歉，未能找到结果", Toast.LENGTH_LONG).show();
			return;
		}
		// 不知道怎么处理两条地理转码同时处理，借用了一下中转ID
		if (changeId == 1)
			pt1 = result.getLocation();
		if (changeId == 2)
			pt2 = result.getLocation();
		if (pt1 != null && pt2 != null) {

			//toPrice();
		}

	}

	@Override
	public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
		// TODO Auto-generated method stub

	}

}
